<!-- xl-qrcode 二维码生成组件 -->
<template>
  <view class="xl-qrcode-container" :style="{ width: `${size}px`, height: `${size}px` }">
    <canvas
      class="qrcode-canvas"
      canvas-id="qrcode"
      :style="{ width: `${size}px`, height: `${size}px` }"
      id="qrcode"
      ref="qrcodeCanvas"
    ></canvas>
    
    <image 
      v-if="(logo || logoSrc) && showLogo" 
      :src="logo || logoSrc" 
      :style="{ 
        width: `${logoSize}px`, 
        height: `${logoSize}px`,
        top: `${(size - logoSize) / 2}px`,
        left: `${(size - logoSize) / 2}px`
      }"
      class="qrcode-logo"
    ></image>
    
    <view class="loading-overlay" v-if="loading">
      <view class="loading-spinner"></view>
    </view>
  </view>
</template>

<script setup>
import { ref, watch, onMounted } from 'vue';
import QRCode from 'qrcode';

// Props
const props = defineProps({
  // 二维码内容
  text: {
    type: String,
    default: '',
    required: true
  },
  // 二维码尺寸
  size: {
    type: Number,
    default: 200
  },
  // 前景色
  foreground: {
    type: String,
    default: '#000000'
  },
  // 背景色
  background: {
    type: String,
    default: '#FFFFFF'
  },
  // Logo地址
  logo: {
    type: String,
    default: ''
  },
  // Logo尺寸
  logoSize: {
    type: Number,
    default: 40
  },
  // 容错级别 L: 7%, M: 15%, Q: 25%, H: 30%
  errorCorrectLevel: {
    type: String,
    default: 'H'
  },
  // 是否显示Logo
  showLogoByDefault: {
    type: Boolean,
    default: false
  }
});

// Refs
const qrcodeCanvas = ref(null);
const canvasContext = ref(null);
const loading = ref(false);
const showLogo = ref(props.showLogoByDefault);
const logoSrc = ref('');

// 生成二维码
const generateQRCode = () => {
  if (!props.text) return;
  
  loading.value = true;
  console.log('开始生成二维码，Logo路径:', props.logo);
  
  try {
    // 使用uni-app 创建Canvas上下文
    const ctx = uni.createCanvasContext('qrcode');
    canvasContext.value = ctx;
    
    // 清空画布
    ctx.clearRect(0, 0, props.size, props.size);
    
    // 绘制背景
    ctx.setFillStyle(props.background);
    ctx.fillRect(0, 0, props.size, props.size);
    
    // 使用qrcode.js库生成二维码数据
    QRCode.toDataURL(props.text, {
      errorCorrectionLevel: props.errorCorrectLevel,
      margin: 1,
      width: props.size,
      color: {
        dark: props.foreground,
        light: props.background
      }
    }, (err, url) => {
      if (err) {
        console.error('Generate QRCode Error:', err);
        loading.value = false;
        return;
      }
      
      // 创建图片对象
      const img = {
        src: url,
        width: props.size,
        height: props.size
      };
      
      // 绘制二维码图片
      ctx.drawImage(img.src, 0, 0, props.size, props.size);
      
      // 绘制Canvas
      ctx.draw(false, () => {
        loading.value = false;
        console.log('二维码绘制完成，准备显示Logo');
        
        // 如果有Logo，显示Logo
        if (props.logo) {
          console.log('检测到Logo，准备显示');
          // 延迟显示logo，确保二维码已绘制完成
          setTimeout(() => {
            showLogo.value = true;
            console.log('Logo显示状态:', showLogo.value);
          }, 50);
        }
      });
    });
  } catch (error) {
    console.error('Generate QRCode Error:', error);
    loading.value = false;
  }
};

// 当text变化时重新生成二维码
watch(() => props.text, (newVal) => {
  if (newVal) {
    generateQRCode();
  }
});

// 当尺寸、颜色等变化时重新生成二维码
watch([
  () => props.size,
  () => props.foreground,
  () => props.background,
  () => props.errorCorrectLevel
], () => {
  if (props.text) {
    generateQRCode();
  }
});

// 组件挂载时生成二维码
onMounted(() => {
  if (props.text) {
    generateQRCode();
  }
});

// 对外暴露接口
defineExpose({
  generateQRCode
});
</script>

<style lang="scss">
.xl-qrcode-container {
  position: relative;
  display: flex;
  justify-content: center;
  align-items: center;
  margin: 0 auto;
  
  .qrcode-canvas {
    position: absolute;
    top: 0;
    left: 0;
    z-index: 1;
  }
  
  .qrcode-logo {
    position: absolute;
    z-index: 2;
    border-radius: 4px;
    box-shadow: 0 0 5px rgba(0, 0, 0, 0.1);
    background-color: #fff;
    padding: 2px;
  }
  
  .loading-overlay {
    position: absolute;
    top: 0;
    left: 0;
    right: 0;
    bottom: 0;
    background-color: rgba(255, 255, 255, 0.7);
    display: flex;
    justify-content: center;
    align-items: center;
    z-index: 3;
    
    .loading-spinner {
      width: 30px;
      height: 30px;
      border: 3px solid #f3f3f3;
      border-top: 3px solid #3498db;
      border-radius: 50%;
      animation: spin 1s linear infinite;
    }
  }
}

@keyframes spin {
  0% { transform: rotate(0deg); }
  100% { transform: rotate(360deg); }
}
</style> 